from django.shortcuts import render,HttpResponse,redirect
from django import views
import openpyxl
from .forms import *
from .baidu_ai_face import *


def get_access_token():
    url = 'https://aip.baidubce.com/oauth/2.0/token?' \
          'grant_type=client_credentials&' \
          'client_id=9jBvknWLKztkaAckXN3REjjn&' \
          'client_secret=nFLcQaMgTvF93GR13BwrTX7G1p5ItGEW'

    # 向百度服务器发起一个请求, 获取响应r
    r = requests.post(url=url)
    access_token = r.json().get('access_token')

    return access_token


def login_error(request):
    return render(request, "login_error.html")


def login_error_login(request):
    return render(request, "login_error_login.html")


class Login(views.View):
    def get(self,request):
        return render(request,"login.html")
    def post(self,request):
        f = UserForms(request.POST)
        name = request.POST.get("username")
        if f.is_valid():
            request.session["username"] = name
            return redirect(index)
        else:
            return redirect("login_error")


class face_login(views.View):
    def get(self,request):
        return render(request,"face_login.html")

    def post(self,request):
        pic = request.POST.get('pic')

        url = "https://aip.baidubce.com/rest/2.0/face/v3/search?" \
              "access_token=%s" % get_access_token()
        header = {
            "Content-Type": "application/json"
        }
        body = {
            "image": pic[23:],
            "image_type": "BASE64",
            "group_id_list": "ss",
            "max_user_num": 1
        }
        r = requests.post(url=url, headers=header, data=body)
        r = r.json()
        if r['error_code'] == 0:
            if r['result']['user_list'][0]['score'] >= 80:
                tel = r['result']['user_list'][0]['user_id']
                username = UserModels.objects.get(tel=tel).username
                request.session["username"] = username
                return redirect(index)
        else:
            return redirect("login")


def regsiter_error(request):
    return render(request,"register_error.html")


class Register(views.View):
    def get(self,request):
        return render(request,"register.html")

    def post(self,request):
        f = RegisterForms(request.POST)
        if f.is_valid():
            f.save()
            return redirect("login")
        else:
            return redirect("register_error")


# 登陆之后进行操作
class face_rigister(views.View):
    def get(self,request):
        name = request.session.get('username')
        return render(request,"face_register.html",{"u":name})

    def post(self,request):
        name = request.session.get('username')
        tel = UserModels.objects.get(username=name).tel
        pic = request.POST.get('pic')
        f = FaceRegister()
        r = f.face(pic[23:], "BASE64", "ss", "%s" % tel)
        if r["error_code"] == 0:
            a = UserInfModels.objects.get(name=name)
            a.face=True
            a.save()
            return redirect("index")
        else:
            return redirect("register")


def index(request):
    name = request.session.get('username')
    if name:  # 首页 ---> 登陆
        u = UserModels.objects.get(username=name)
        if UserInfModels.objects.filter(username=name).exists():
            return render(request, 'index.html', {'u': u})
        else:
            return redirect("alter")

    else:  # 未登录 ---> 跳转到登陆页面
        return redirect('login')


def exit(request):
    request.session.flush()
    return redirect(index)


def see(request):
    name = request.session.get('username')
    u = UserInfModels.objects.get(name=name)
    return render(request, "see.html", {"u": u})


class alter(views.View):
    def get(self,request):
        return render(request, "alter.html")

    def post(self, request):
        name = request.session.get('username')
        username = request.POST.get("username")
        sex = request.POST.get("sex")
        age = request.POST.get("age")
        photo = request.FILES.get("photo")
        money = request.POST.get("money")
        married = request.POST.get("married")
        children = request.POST.get("children")
        house = request.POST.get("house")
        UserInfModels.objects.create(username=username, sex=sex, age=age, photo=photo, money=money, married=married, children=children, house=house, name=name)
        return redirect(index)


class alter_inf(views.View):
    def get(self, request):
        name = request.session.get('username')
        u = UserInfModels.objects.get(name=name)
        return render(request, "alert_inf.html", {"u":u})

    def post(self, request):
        name = request.session.get('username')
        username = request.POST.get("username")
        sex = request.POST.get("sex")
        age = request.POST.get("age")
        photo = request.FILES.get("photo")
        money = request.POST.get("money")
        married = request.POST.get("married")
        children = request.POST.get("children")
        house = request.POST.get("house")
        print(type(photo))
        a = UserInfModels.objects.filter(username=name)
        a.update(sex=sex, age=age, photo=photo, money=money, married=married, children=children, house=house, name=username)
        return redirect(index)


def revamp(request):
    if request.method == "GET":
        name = request.session.get('username')
        u = UserInfModels.objects.get(name=name)
        return render(request,"revamp.html",{"u": u})
    else:
        name = request.session.get('username')
        username = request.POST.get("username")
        sex = request.POST.get("sex")
        age = request.POST.get("age")
        photo = request.FILES.get("photo")
        money = request.POST.get("money")
        married = request.POST.get("married")
        children = request.POST.get("children")
        house = request.POST.get("house")
        u = UserInfModels.objects.filter(username=name)
        u.update(username=username, sex=sex, age=age, photo=photo, money=money, married=married, children=children, house=house)
        return redirect(index)


def high_sex(request):
    if request.method == "GET":
        name = request.session.get('username')
        if name:
            now_sex = UserInfModels.objects.get(username=name).sex
            if now_sex == "男":
                a = UserInfModels.objects.filter(sex="女")
            else:
                a = UserInfModels.objects.filter(sex="男")
            return render(request,"high sex.html", {"a": a, "u": name,})
        else:
            return redirect("login_error_login")
    else:
        age = request.POST.get("age")
        money = request.POST.get("money")
        married = request.POST.get("married")
        children = request.POST.get("children")
        house = request.POST.get("house")
        name = request.session.get('username')
        a = UserInfModels.objects.get(name=name).sex
        b = 1
        if a == "男":
            b = "女"
        else:
            b = "男"
        inf = UserInfModels.objects.filter(sex=b)
        if age!= "错误":
            inf = UserInfModels.objects.filter(age=age)
        if money != "错误":
            print(inf)
            inf = inf.filter(money=money)
        if married != "错误":
            inf = inf.filter(married=married)
        if children != "错误":
            inf = inf.filter(children=children)
        if house != "错误":
            inf = inf.filter(house=house)
        return render(request, "high sex.html", {"inf":inf})


def see_p(request):
    name = request.session.get('username')
    p = UserInfModels.objects.get(username=name).photo
    return redirect('http://127.0.0.1:8000/media/%s' % p)


def collect_false(request):
    username = request.session.get('username')
    u = UserInfModels.objects.get(name=username)
    return render(request,"collect_False.html",{"u":u})


# def collect_delete(request, cid):
#     a = UserInfModels.objects.get(id=cid)
#     name = request.session.get("username")
#     n_id = UserInfModels.objects.get(name=name).id
#     b = collect_all(this_u=n_id,this_c=a)
#     print(b)
#     # b.save()
#     return redirect(collect)


class collect(views.View):
    def get(self,request):
        username = request.session.get('username')
        u = UserInfModels.objects.get(name=username)
        if username:
            uid = UserInfModels.objects.get(name=username).id
            # 当前用户关注的用户
            user = collect_all.objects.filter(this_u=uid)

            return render(request, "collect.html", {"user": user, "u": u})
        else:
            return redirect("collect_false")

    def post(self,request):
        name = request.POST.get("name")
        username = request.session.get('username')
        uid = UserInfModels.objects.get(name=username).id
        # 当前用户关注的用户
        user = collect_all.objects.filter(this_u=uid)

        if UserInfModels.objects.filter(name=name).exists():
            a = UserInfModels.objects.filter(name=name)
            return render(request, "collect_r.html", {"us": a, "u": user})
        else:
            return redirect("collect_false")


def collect_r(request, cid):
    name = request.session.get("username")
    uid = UserInfModels.objects.get(name=name).id
    print(cid)
    a = collect_all(this_u=uid)
    c = UserInfModels.objects.get(id=cid)
    a.this_c=c
    if collect_all.objects.filter(this_u=uid,this_c=c.id):
        return redirect("collect")
    else:
        a.save()
        return redirect("collect")


def screen_error(request):
    return render(request,"screen_error.html")


class screen(views.View):
    def get(self,request):
        a = request.session.get("username")
        if a:
            return render(request, "screen.html",{"u": a})
        else:
            return redirect("login_error_login")
    def post(self,request):
        name = request.session.get("username")
        a = UserInfModels.objects.get(name=name).sex
        if a == "男":
            b = "女"
        else:
            b = "男"
        age = request.POST.get("age")
        money = request.POST.get("money")
        married = request.POST.get("married")
        children = request.POST.get("children")
        house = request.POST.get("house")
        res = UserInfModels.objects.filter(age=age, money=money, married=married, children=children, house=house,sex=b)
        if res:
            return render(request, "screen_r.html", {"res": res})
        else:
            return redirect(screen_error)



def load(request):
    wb = openpyxl.Workbook()  # 工作簿
    ws = wb.active

    ws["A1"].value = "姓名"
    ws["B1"].value = "性别"
    ws["C1"].value = "年龄"
    ws["D1"].value = "年薪"
    ws["E1"].value = "婚否"
    ws["F1"].value = "子女"
    ws["G1"].value = "房产"
    row = 2
        # print(u)
        # c = UserInfModels.objects.get(id=u.this_c)
    username = request.session.get('username')
    uid = UserInfModels.objects.get(name=username).id
    # 当前用户关注的用户
    user = collect_all.objects.filter(this_u=uid)
    for u in user:
        ws["A" + str(row)].value = u.this_c.name
        ws["B" + str(row)].value = u.this_c.sex
        ws["C" + str(row)].value = u.this_c.age
        ws["D" + str(row)].value = u.this_c.money
        ws["E" + str(row)].value = u.this_c.married
        ws["F" + str(row)].value = u.this_c.children
        ws["G" + str(row)].value = u.this_c.house
        row += 1

    wb.save("收藏信息表.xlsx")

    f = open("收藏信息表.xlsx", "rb")
    p = HttpResponse()
    p.content = f
    p["Content-Type"] = "application/octet-stream"
    p["Content-Disposition"] = "attachment;filename='收藏信息表.xlsx'"

    return p


def leave(request, cid):
        if request.method == "GET":
            name = request.session.get("username")
            us = UserInfModels.objects.get(id=cid)
            return render(request, "leave.html", {"us": us,"u": name})
        else:
            text = request.POST.get("text")
            name = request.session.get("username")
            name = UserInfModels.objects.get(username=name).id
            c = UserInfModels.objects.get(id=cid)
            a = Leave(content=text,this_u=name)
            a.this_c = c
            a.save()
            return redirect("index")


def leave_c(request):
    name = request.session.get("username")
    if name:
        a = UserInfModels.objects.get(username=name)#现在登陆的用户
        us = Leave.objects.filter(this_c=a.id) #获取到的被留言的信息
        c = []
        for u in us:
            print(u.id)
            a = UserInfModels.objects.get(id=u.this_u).name
            c.append(a)
        return render(request,"leave_c.html", {"us": us, "cs": c, "u":name})
    else:
        return redirect("login_error_login")


def replay(request, cid):
    if request.method == "GET":
        us = UserInfModels.objects.get(id=cid)
        return render(request, "replay.html", {"us": us})
    else:
        text = request.POST.get("text")
        name = request.session.get("username")
        name = UserInfModels.objects.get(username=name).id
        c = UserInfModels.objects.get(id=cid)
        a = Leave(content=text, this_u=name)
        a.this_c = c
        a.save()
        return redirect("index")